<template>
  <div class="transactions-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <a-row :gutter="24" align="middle">
        <a-col flex="1">
          <h2>交易记录</h2>
          <p class="page-description">查看和管理所有交易记录</p>
        </a-col>
        <a-col>
          <a-space>
            <a-button @click="loadTransactions">
              <template #icon><SyncOutlined /></template>
              刷新
            </a-button>
            <a-button type="primary" @click="exportTransactions">
              <template #icon><DownloadOutlined /></template>
              导出记录
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 交易统计 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="总交易数"
            :value="transactionStats.total"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix><CreditCardOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="成功交易"
            :value="transactionStats.completed"
            :value-style="{ color: '#52c41a' }"
          >
            <template #prefix><CheckCircleOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="处理中"
            :value="transactionStats.pending"
            :value-style="{ color: '#faad14' }"
          >
            <template #prefix><LoadingOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="交易总额"
            :value="transactionStats.totalAmount"
            :precision="0"
            suffix="元"
            :value-style="{ color: '#f5222d' }"
          >
            <template #prefix><MoneyCollectOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 搜索和筛选 -->
    <a-card class="search-card" size="small">
      <a-form :model="searchForm" layout="inline" @finish="handleSearch">
        <a-form-item label="交易号" name="keyword">
          <a-input
            v-model="searchForm.keyword"
            placeholder="输入交易号或订单号"
            allow-clear
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="交易类型" name="type">
          <a-select
            v-model="searchForm.type"
            placeholder="选择类型"
            allow-clear
            style="width: 120px"
          >
            <a-select-option value="payment">支付</a-select-option>
            <a-select-option value="refund">退款</a-select-option>
            <a-select-option value="cancel_refund">取消退款</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="交易状态" name="status">
          <a-select
            v-model="searchForm.status"
            placeholder="选择状态"
            allow-clear
            style="width: 120px"
          >
            <a-select-option value="pending">处理中</a-select-option>
            <a-select-option value="completed">已完成</a-select-option>
            <a-select-option value="failed">失败</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="支付方式" name="method">
          <a-select
            v-model="searchForm.method"
            placeholder="选择方式"
            allow-clear
            style="width: 120px"
          >
            <a-select-option value="alipay">支付宝</a-select-option>
            <a-select-option value="wechat_pay">微信支付</a-select-option>
            <a-select-option value="bank_transfer">银行转账</a-select-option>
            <a-select-option value="credit_card">信用卡</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="金额范围" name="amountRange">
          <a-input-number
            v-model="searchForm.minAmount"
            placeholder="最低金额"
            style="width: 100px"
          />
          <span style="margin: 0 8px">-</span>
          <a-input-number
            v-model="searchForm.maxAmount"
            placeholder="最高金额"
            style="width: 100px"
          />
        </a-form-item>
        <a-form-item label="日期范围" name="dateRange">
          <a-range-picker v-model="searchForm.dateRange" style="width: 240px" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 交易记录表格 -->
    <a-card size="small">
      <a-table
        :columns="columns"
        :data-source="transactions"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'transaction'">
            <div class="transaction-info">
              <div class="transaction-id">{{ record.id }}</div>
              <div class="order-link">
                <a @click="viewOrderDetail(record.orderId)">
                  订单: {{ record.orderId }}
                </a>
              </div>
              <div class="listing-title">{{ record.listingTitle }}</div>
            </div>
          </template>

          <template v-else-if="column.key === 'type'">
            <div class="type-info">
              <a-tag :color="getTypeColor(record.type)">
                {{ record.typeName }}
              </a-tag>
              <div class="description">{{ record.description }}</div>
            </div>
          </template>

          <template v-else-if="column.key === 'amount'">
            <div class="amount-info">
              <div class="main-amount" :class="{ negative: record.amount < 0 }">
                {{ record.amount >= 0 ? '+' : '00' }}¥{{
                  formatPrice(Math.abs(record.amount))
                }}
              </div>
              <div class="currency">{{ record.currency }}</div>
              <div v-if="record.platformFee" class="platform-fee">
                平台费: ¥{{ formatPrice(Math.abs(record.platformFee)) }}
              </div>
            </div>
          </template>

          <template v-else-if="column.key === 'participants'">
            <div class="participants-info">
              <div class="participant">
                <span class="label">付款方:</span>
                <a-space size="small">
                  <a-avatar :size="20" :src="record.payer.avatar" />
                  <span>{{ record.payer.name }}</span>
                </a-space>
              </div>
              <div class="participant">
                <span class="label">收款方:</span>
                <a-space size="small">
                  <a-avatar :size="20" :src="record.payee.avatar" />
                  <span>{{ record.payee.name }}</span>
                </a-space>
              </div>
            </div>
          </template>

          <template v-else-if="column.key === 'method'">
            <div class="method-info">
              <a-tag>{{ getPaymentMethodName(record.method) }}</a-tag>
              <div v-if="record.paymentDetails.bankName" class="bank-info">
                {{ record.paymentDetails.bankName }}
                {{ record.paymentDetails.cardNumber }}
              </div>
              <div v-if="record.paymentDetails.tradeNo" class="trade-no">
                {{ record.paymentDetails.tradeNo }}
              </div>
            </div>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ record.statusName }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'time'">
            <div class="time-info">
              <div class="created-time">
                创建: {{ formatDateTime(record.createdAt) }}
              </div>
              <div v-if="record.completedAt" class="completed-time">
                完成: {{ formatDateTime(record.completedAt) }}
              </div>
            </div>
          </template>

          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button size="small" @click="viewTransactionDetail(record)">
                详情
              </a-button>
              <a-dropdown v-if="getTransactionActions(record).length > 0">
                <a-button size="small"> 操作 <DownOutlined /> </a-button>
                <template #overlay>
                  <a-menu @click="handleTransactionAction($event, record)">
                    <a-menu-item
                      v-for="action in getTransactionActions(record)"
                      :key="action.key"
                      :disabled="action.disabled"
                    >
                      {{ action.label }}
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 交易详情弹窗 -->
    <a-modal
      v-model:visible="showDetailModal"
      title="交易详情"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedTransaction" class="transaction-detail">
        <!-- 交易基本信息 -->
        <a-descriptions title="交易信息" :column="2" bordered size="small">
          <a-descriptions-item label="交易号">
            {{ selectedTransaction.id }}
          </a-descriptions-item>
          <a-descriptions-item label="订单号">
            <a @click="viewOrderDetail(selectedTransaction.orderId)">
              {{ selectedTransaction.orderId }}
            </a>
          </a-descriptions-item>
          <a-descriptions-item label="交易类型">
            <a-tag :color="getTypeColor(selectedTransaction.type)">
              {{ selectedTransaction.typeName }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="交易状态">
            <a-tag :color="getStatusColor(selectedTransaction.status)">
              {{ selectedTransaction.statusName }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="交易描述" :span="2">
            {{ selectedTransaction.description }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 金额信息 -->
        <a-descriptions
          title="金额信息"
          :column="2"
          bordered
          size="small"
          style="margin-top: 16px"
        >
          <a-descriptions-item label="交易金额">
            <span :class="{ negative: selectedTransaction.amount < 0 }">
              {{ selectedTransaction.amount >= 0 ? '+' : '' }}¥{{
                formatPrice(Math.abs(selectedTransaction.amount))
              }}
            </span>
          </a-descriptions-item>
          <a-descriptions-item label="币种">
            {{ selectedTransaction.currency }}
          </a-descriptions-item>
          <a-descriptions-item label="平台费">
            ¥{{ formatPrice(Math.abs(selectedTransaction.platformFee || 0)) }}
          </a-descriptions-item>
          <a-descriptions-item label="卖家实收">
            ¥{{
              formatPrice(Math.abs(selectedTransaction.sellerReceives || 0))
            }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 交易双方 -->
        <a-row :gutter="16" style="margin-top: 16px">
          <a-col :span="12">
            <a-descriptions title="付款方" :column="1" bordered size="small">
              <a-descriptions-item label="名称">
                {{ selectedTransaction.payer.name }}
              </a-descriptions-item>
              <a-descriptions-item label="账户">
                {{ selectedTransaction.payer.account }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :span="12">
            <a-descriptions title="收款方" :column="1" bordered size="small">
              <a-descriptions-item label="名称">
                {{ selectedTransaction.payee.name }}
              </a-descriptions-item>
              <a-descriptions-item label="账户">
                {{ selectedTransaction.payee.account }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
        </a-row>

        <!-- 支付信息 -->
        <a-descriptions
          title="支付信息"
          :column="2"
          bordered
          size="small"
          style="margin-top: 16px"
        >
          <a-descriptions-item label="支付方式">
            {{ getPaymentMethodName(selectedTransaction.method) }}
          </a-descriptions-item>
          <a-descriptions-item label="验证状态">
            {{ selectedTransaction.paymentDetails.verificationCode }}
          </a-descriptions-item>
          <a-descriptions-item
            v-if="selectedTransaction.paymentDetails.bankName"
            label="银行"
          >
            {{ selectedTransaction.paymentDetails.bankName }}
          </a-descriptions-item>
          <a-descriptions-item
            v-if="selectedTransaction.paymentDetails.cardNumber"
            label="卡号"
          >
            {{ selectedTransaction.paymentDetails.cardNumber }}
          </a-descriptions-item>
          <a-descriptions-item
            v-if="selectedTransaction.paymentDetails.tradeNo"
            label="第三方交易号"
            :span="2"
          >
            {{ selectedTransaction.paymentDetails.tradeNo }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 时间信息 -->
        <a-descriptions
          title="时间信息"
          :column="2"
          bordered
          size="small"
          style="margin-top: 16px"
        >
          <a-descriptions-item label="创建时间">
            {{ formatDateTime(selectedTransaction.createdAt) }}
          </a-descriptions-item>
          <a-descriptions-item label="完成时间">
            {{
              selectedTransaction.completedAt
                ? formatDateTime(selectedTransaction.completedAt)
                : '未完成'
            }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 备注信息 -->
        <div v-if="selectedTransaction.notes" style="margin-top: 16px">
          <h4>备注信息</h4>
          <a-alert :message="selectedTransaction.notes" type="info" />
        </div>

        <!-- 退款原因 -->
        <div v-if="selectedTransaction.refundReason" style="margin-top: 16px">
          <h4>退款原因</h4>
          <a-alert :message="selectedTransaction.refundReason" type="warning" />
        </div>

        <!-- 取消原因 -->
        <div v-if="selectedTransaction.cancelReason" style="margin-top: 16px">
          <h4>取消原因</h4>
          <a-alert :message="selectedTransaction.cancelReason" type="error" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import { getTransactions } from '#/api/resource-center';

// 响应式数据
const loading = ref(false);
const showDetailModal = ref(false);
const selectedTransaction = ref(null);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: undefined,
  status: undefined,
  method: undefined,
  minAmount: undefined,
  maxAmount: undefined,
  dateRange: undefined,
});

// 交易记录列表
const transactions = ref([]);

// 交易统计
const transactionStats = computed(() => {
  const stats = {
    total: transactions.value.length,
    completed: 0,
    pending: 0,
    totalAmount: 0,
  };

  transactions.value.forEach((txn) => {
    if (txn.status === 'completed') {
      stats.completed++;
    } else if (txn.status === 'pending') {
      stats.pending++;
    }

    if (txn.status === 'completed' && txn.amount > 0) {
      stats.totalAmount += txn.amount;
    }
  });

  return stats;
});

// 表格列配置
const columns = [
  {
    title: '交易信息',
    key: 'transaction',
    width: 250,
  },
  {
    title: '类型',
    key: 'type',
    width: 120,
  },
  {
    title: '金额',
    key: 'amount',
    width: 120,
  },
  {
    title: '交易双方',
    key: 'participants',
    width: 200,
  },
  {
    title: '支付方式',
    key: 'method',
    width: 150,
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
  },
  {
    title: '时间',
    key: 'time',
    width: 180,
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    fixed: 'right',
  },
];

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: number[]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
});

// 格式化价格
const formatPrice = (price: number) => {
  if (price >= 10000) {
    return (price / 10000).toFixed(1) + '万';
  }
  return price.toLocaleString();
};

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  return new Date(dateString).toLocaleString();
};

// 获取交易类型颜色
const getTypeColor = (type: string) => {
  const colorMap = {
    payment: 'blue',
    refund: 'orange',
    cancel_refund: 'red',
  };
  return colorMap[type] || 'default';
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap = {
    pending: 'orange',
    completed: 'success',
    failed: 'error',
  };
  return colorMap[status] || 'default';
};

// 获取支付方式名称
const getPaymentMethodName = (method: string) => {
  const methodMap = {
    alipay: '支付宝',
    wechat_pay: '微信支付',
    bank_transfer: '银行转账',
    credit_card: '信用卡',
    system: '系统',
    '': '未知',
  };
  return methodMap[method] || method;
};

// 获取交易可用操作
const getTransactionActions = (transaction: any) => {
  const actions = [];

  if (transaction.status === 'pending') {
    actions.push({ key: 'cancel', label: '取消交易' });
  }

  if (transaction.status === 'completed' && transaction.type === 'payment') {
    actions.push({ key: 'refund', label: '申请退款' });
  }

  return actions;
};

// 处理交易操作
const handleTransactionAction = (
  { key }: { key: string },
  transaction: any,
) => {
  console.log('交易操作:', key, transaction.id);

  switch (key) {
    case 'cancel':
      message.info('取消交易');
      break;
    case 'refund':
      message.info('申请退款');
      break;
  }
};

// 查看交易详情
const viewTransactionDetail = (transaction: any) => {
  selectedTransaction.value = transaction;
  showDetailModal.value = true;
};

// 查看订单详情
const viewOrderDetail = (orderId: string) => {
  console.log('查看订单:', orderId);
  // 可以跳转到订单详情页或者打开订单详情弹窗
};

// 导出交易记录
const exportTransactions = () => {
  message.info('导出功能开发中...');
};

// 加载交易记录
const loadTransactions = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      page: pagination.current,
      pageSize: pagination.pageSize,
    };

    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      (params as any).startDate = searchForm.dateRange[0].format('YYYY-MM-DD');
      (params as any).endDate = searchForm.dateRange[1].format('YYYY-MM-DD');
    }

    const result = await getTransactions(params);
    transactions.value = result.items || [];
    pagination.total = result.total || 0;
  } catch (error) {
    console.error('获取交易记录失败:', error);
    message.error('获取交易记录失败');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  loadTransactions();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    type: undefined,
    status: undefined,
    method: undefined,
    minAmount: undefined,
    maxAmount: undefined,
    dateRange: undefined,
  });
  pagination.current = 1;
  loadTransactions();
};

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadTransactions();
};

// 初始化
onMounted(() => {
  loadTransactions();
});
</script>

<style scoped>
.transactions-page {
  padding: 16px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-description {
  margin: 4px 0 0 0;
  color: #6b7280;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 24px;
}

.search-card {
  margin-bottom: 16px;
}

.transaction-info {
  padding: 4px 0;
}

.transaction-id {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
}

.order-link {
  font-size: 12px;
  margin-bottom: 4px;
}

.order-link a {
  color: #1890ff;
}

.listing-title {
  font-size: 12px;
  color: #6b7280;
}

.type-info {
  text-align: center;
}

.description {
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
}

.amount-info {
  text-align: right;
}

.main-amount {
  font-size: 16px;
  font-weight: 600;
  color: #52c41a;
}

.main-amount.negative {
  color: #f5222d;
}

.currency {
  font-size: 12px;
  color: #6b7280;
  margin-top: 2px;
}

.platform-fee {
  font-size: 12px;
  color: #fa8c16;
  margin-top: 2px;
}

.participants-info {
  font-size: 12px;
}

.participant {
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  color: #6b7280;
  min-width: 50px;
}

.method-info {
  text-align: center;
}

.bank-info {
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
}

.trade-no {
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
  word-break: break-all;
}

.time-info {
  font-size: 12px;
}

.created-time {
  color: #1f2937;
  margin-bottom: 4px;
}

.completed-time {
  color: #6b7280;
}

.transaction-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.negative {
  color: #f5222d !important;
}
</style>
